<?php
namespace app\wenchuang\controller;

use app\wenchuang\model\BannerModel;
use app\wenchuang\validate\BannerValidate;
use cmf\controller\AdminBaseController;

class BannerController extends AdminBaseController
{
    // 列表显示
    public function index()
    {
        $banner = BannerModel::order('list_order',  'desc')->select();
        $this->assign('banner', $banner);
        return $this->fetch();
    }



    // 显示添加页面
    public function add()
    {
        return $this->fetch();
    }

    // 添加保存
    public function addPost()
    {
        $data = $this->request->param();
        // 验证数据
        $validate = new BannerValidate();
        $result = $validate->scene('add')->check($data);
        if ($result !== true) {
            $this->error($validate->getError());
        }
        // 存库
        $bannerModel = New BannerModel();
        if ($bannerModel->save($data)) {
            $this->success('添加成功', 'Banner/index');
        }
        $this->error('添加失败');
    }

    // 排序
    public function listOrder()
    {
        parent::listOrders(new BannerModel());
        $this->success('排序成功');
    }

    // 删除
    public function softDelete()
    {
        $id = input('id');
        $bannerModel = New BannerModel();
        // 查询要删除的数据
        $banner = $bannerModel->where('id', '=', $id)->find();
        if ($banner->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    // 显示修改页面
    public function edit()
    {
        $id = $this->request->param('id');
        $banner = BannerModel::find($id);
        $this->assign('banner', $banner);
        return $this->fetch();
    }

    // 编辑保存
    public function editPost()
    {
        $data = $this->request->param();
        // 验证数据
        $validate = new BannerValidate();
        $result = $validate->scene('add')->check($data);
        if ($result !== true) {
            $this->error($validate->getError());
        }
        // 存库
        $bannerModel = New BannerModel();
        $banner = $bannerModel->where('id', '=', $data['id'])->find();
        $banner->image = $data['image'];
        $banner->url = $data['url'];
        if ($banner->save()) {
            $this->success('保存成功', 'Banner/index');
        }
        $this->error('保存失败');
    }
}